<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">
        首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item @click.native="goPage('/goods')">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods/edit' }">修改商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片区域-->
    <el-card>
      <el-alert
        title="修改商品信息"
        type="info"
        center
        show-icon
        :closable="false">
      </el-alert>
      <!--tabs栏区域-->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
        <el-tabs v-model="activeIndex" :tab-position="'top'"
                 :before-leave="beforeTabLeave"
                 @tab-click="tabClick">
          <el-tab-pane label="基本信息" name="0" :style="'height:'+windowHeights+'px;'">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cate">
              <el-input disabled v-model="cateStr" style="width:250px"></el-input>
              <el-cascader
                ref="cascaderAddr"
                v-model="addForm.goods_cate"
                :options="cateList"
                :props="cateProps"
                @change="handleChange" clearable @visible-change="clickCascader"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1" :style="'height:'+windowHeights+'px;'">
            <!--渲染表单item项-->
            <el-form-item :label="item.attr_name" :key="item.attr_id" v-for="item in manyTableData">
              <!--复选框组-->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="it" :key="i" v-for="(it, i) in item.attr_vals"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2" :style="'height:'+windowHeights+'px;'">
            <el-form-item :key="item.attr_id" :label="item.attr_name" v-for="item in onlyTableData">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3" :style="'height:'+windowHeights+'px;'">
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              :headers="headersObj"
              :on-success="handleSuccess"
              :before-upload="beforeUpload"
              drag
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png/gif文件，且至少上传1张,大小不超过5MB</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4" :style="'height:'+windowHeights+'px;'">
            <!--富文本编辑器组件-->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <!--添加商品按钮-->
            <el-button type="primary" class="btnAdd" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!--图片预览-->
    <el-dialog
      title="图片预览"
      :visible.sync="previewVisible"
      width="50%">
      <img :src="previewPath" alt="图片预览" class="previewImg">
    </el-dialog>
  </div>
</template>

<script>
  // eslint-disable-next-line
  import _ from 'lodash'

  export default {
    name: 'Add',
    data() {
      return {
        id: this.$route.query.key,
        // 步骤条和el-tabs标签页联动值
        activeIndex: '0',
        visibleCascader: false,
        // 默认显示的商品分类参数
        cateStr: '',
        // 添加商品的表单数据对象
        addForm: {
          goods_name: '',
          goods_price: 0,
          goods_weight: 0,
          goods_number: 0,
          // 商品所属的分类数组
          goods_cate: [],
          // 图片的数组
          pics: [],
          // 商品详情的描述
          goods_introduce: '',
          attrs: []
        },
        // 添加商品的表单数据对象规则校验
        addFormRules: {
          goods_name: [
            { required: true, message: '请输入商品名称', trigger: 'blur' }
          ],
          goods_price: [
            { required: true, message: '请输入商品价格', trigger: 'blur' },
            {
              validator: (rule, value, callback) => {
                const pattern = /^[0-9]+(\.[0-9]{1,2})?$/
                if (!pattern.test(value)) {
                  callback(new Error('请输入正整数(只允许带两位小数点)'))
                }
                callback()
              },
              trigger: 'blur'
            }
          ],
          goods_weight: [
            { required: true, message: '请输入商品重量', trigger: 'blur' },
            {
              validator: (rule, value, callback) => {
                const pattern = /^[0-9]+(\.[0-9]{1,2})?$/
                if (!pattern.test(value)) {
                  callback(new Error('请输入正整数(只允许带两位小数点)'))
                }
                callback()
              },
              trigger: 'blur'
            }
          ],
          goods_number: [
            { required: true, message: '请输入商品数量', trigger: 'blur' },
            {
              validator: (rule, value, callback) => {
                const pattern = /^[+]{0,1}(\d+)$/
                if (!pattern.test(value)) {
                  callback(new Error('请输入正整数'))
                }
                callback()
              }
            }
          ],
          goods_cate: [
            { required: true, message: '请选择商品分类', trigger: 'blur' }
          ]
        },
        // 当前窗口高度
        getWindowHeight: 0,
        cateList: [],
        // 级联选择框的配置对象
        cateProps:
          {
          value: 'cat_id',
          label: 'cat_name',
          children: 'children',
          expandTrigger: 'hover'
        },
        cateProps2: [],
        // 动态参数列表数据
        manyTableData: [],
        // 静态属性列表数
        onlyTableData: [],
        // 上传图片URL地址
        uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
        // 图标上传组件的headers请求头对象
        headersObj: {
          Authorization: window.sessionStorage.getItem('token')
        },
        // 图片预览的地址路径
        previewPath: '',
        // 图片预览对话框
        previewVisible: false,
        // 图片显示地址栏
      fileList: []
      }
    },
    beforeCreate() {

    },
    created() {
      this.queryCurrentProduct()
      this.getCatList()
    },
    computed: {
      // 获取当前窗口高度
      windowHeights() {
        document.documentElement.style.overflowY = 'hidden'
        return document.documentElement.clientHeight - 150 || document.body.clientHeight - 150
      },
      cateId() {
        if (this.addForm.goods_cate.length === 3) {
          return this.addForm.goods_cate[2]
        }
        return null
      }
    },
    methods: {
      // 跳转页面
      goPage(pageStr) {
        this.$router.push(pageStr)
      },
      // 级联选择器点击事件
      clickCascader() {

      },
      // 根据id查询当前商品数据分类信息
      async queryCurrentProduct() {
        const { data: res } = await this.$http.get(`goods/${this.id}`)
        if (res.meta.status !== 200) {
          return this.$message.error('获取商品数据失败!')
        }
        console.log(res.data)
        // 获取商品图片地址
        res.data.pics.forEach((item, index) => {
          const fileName = item.pics_sma_url.split('/')
          console.log(fileName[fileName.length - 1])
          const fileNames = { name: fileName[fileName.length - 1], url: item.pics_sma_url }
          this.fileList.push(fileNames)
        })
        this.addForm = res.data
        // 商品分类参数id转为数组
        const id = res.data.goods_cat.split(',')
        this.addForm.goods_cate = id
        console.log(id)
        const { data: one } = await this.$http.get(`categories/${id[0]}`)
        if (one.meta.status !== 200) {
          return this.$message.error('获取商品父级分类失败!')
        }
        const { data: two } = await this.$http.get(`categories/${id[1]}`)
        if (two.meta.status !== 200) {
          return this.$message.error('获取商品父级分类失败!')
        }
        const { data: three } = await this.$http.get(`categories/${id[2]}`)
        if (three.meta.status !== 200) {
          return this.$message.error('获取商品分类失败!')
        }
        if (id.length <= 3) {
          this.cateStr = `${one.data.cat_name}/${two.data.cat_name}/${three.data.cat_name}`
        } else if (id.length <= 2) {
          this.cateStr = `${one.data.cat_name}/${two.data.cat_name}`
        } else {
          this.cateStr = `${one.data.cat_name}`
        }
        /*
        const { data: cate } = await this.$http.get(`categories/${res.data.cat_id}`)
        if (cate.meta.status !== 200) {
          return this.$message.error('获取商品分类失败!')
        }

        const { data: pid } = await this.$http.get(`categories/${cate.data.cat_pid}`)
        if (pid.meta.status !== 200) {
          return this.$message.error('获取商品父级分类失败!')
        }
        if (res.data.cat_name !== undefined && res.data.cat_name !== 'undefined' && res.data.cat_name !== null) {
          this.cateStr = `${pid.data.cat_name}/${cate.data.cat_name}/${res.data.cat_name}`
        } else if (res.data.cat_name === undefined || res.data.cat_name === 'undefined' || res.data.cat_name === null) {
          this.cateStr = `${cpid.data.cat_name}/${pid.data.cat_name}/${cate.data.cat_name}`
        } else {
          this.cateStr = `${pid.data.cat_name}`
        }
*/
     /*   console.log(res)
        console.log(one)
        console.log(two)
        console.log(three) */
      },
      // 获取所有商品分类数据
      async getCatList() {
        const { data: res } = await this.$http.get('categories')
        if (res.meta.status !== 200) {
          return this.$message.error('获取商品分类数据失败!')
        }
        this.cateList = res.data
      },
      // 级联选择框选中项变化,会触发这个函数
      handleChange() {
          if (this.addForm.goods_cate.length !== 3) {
            this.addForm.goods_cate = []
            return this.$message.error('只允许选择第三级分类!')
          }
      },
      // 切换标签之前的钩子，若返回 false 或者返回 Promise 且被 reject，则阻止切换
      beforeTabLeave(activeName, oldActiveName) {
        //  console.log('即将离开的标签页名字是:' + oldActiveName)
        // console.log('即将进入的标签页名字是:' + activeName)
        if (oldActiveName === '0' && this.addForm.goods_cate.length !== 3) {
          this.$message.error('请先选择商品分类!')
          return false
        }
      },
      // 获取动态参数列表
      async getCateManyList() {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'many' } })
        if (res.meta.status !== 200) {
          return this.$message.error('获取动态参数列表失败!')
        }
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyTableData = res.data
      },
      // 获取静态参数 only
      async getCateOnlyList() {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'only' } })
        if (res.meta.status !== 200) {
          return this.$message.error('获取静态属性失败!')
        }
        this.onlyTableData = res.data
      },
      // tab 被选中时触发
      tabClick() {
        // console.log(this.activeIndex)
        // 证明访问的是动态参数面板
        if (this.activeIndex === '1') {
          this.getCateManyList()
        } else if (this.activeIndex === '2') {
          this.getCateOnlyList()
        }
      },
      // 处理图片预览效果
      handlePreview(file) {
        this.previewPath = file.response.data.url
        this.previewVisible = true
      },
      // 处理移除图片的事件
      handleRemove(file, fileList) {
        // 获取将要被删除的图片临时路径
        const filePath = file.response.data.tmp_path
        // 从pics数组中找到图片对应的索引值
        const index = this.addForm.pics.findIndex(x => x.pic === filePath)
        // 调用数组splice 方法把图片对象信息从pics数组中移除
        this.addForm.pics.splice(index)
      },
      // 上传文件前，判断文件大小类型 jpg ，png ，text ，gif
      beforeUpload(file) {
        const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
        const isImage = types.includes(file.type)
        const isLtSize = file.size / 1024 / 1024 < 5
        if (!isImage) {
          this.$message.error('上传图片只能是 JPG、GIF、BMP、PNG 格式!')
          return false
        } else if (!isLtSize) {
          this.$message.error('上传图片大小不能超过 5MB!')
          return false
        }
        // 获取文件名
        // console.log(file.name.substring(0, file.name.lastIndexOf('.')))
        // 只获取后缀名
        /*
        const suffix = file.name.substring(file.name.lastIndexOf('.') + 1)
        // console.log(file.name.substring(file.name.lastIndexOf('.') + 1))
        if (suffix === 'jpg' || suffix === 'png' || suffix === 'gif' || suffix === 'jpeg') {
          this.$message.success('上传成功!')
          return true
        }
        */
        this.$message.success('上传成功!')
        return true
      },
      // 监听图片上传成功的事件
      handleSuccess(response) {
        // 拼接得到一个图片信息对象
        const picsInfo = {
          pic: response.data.tmp_path
        }
        // 将图片信息push 到pics数组中
        this.addForm.pics.push(picsInfo)
      },
      // 添加商品按钮
      async add() {
        /*
         this.$refs.addFormRef.validate(async valid => {
          if (!valid) {
            return this.$message.error('请填写必要的表单项!')
          }
        // 执行添加的业务逻辑
        // 使用lodash 拷贝数据 cloneDeep(obj)
        const form = _.cloneDeep(this.addForm)
        form.goods_cate = form.goods_cate.join(',')
        // 处理动态参数
        this.manyTableData.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals.join(' ') }
          this.addForm.attrs.push(newInfo)
        })
        // 处理静态属性
        this.onlyTableData.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
          this.addForm.attrs.push(newInfo)
        })
        // 发起请求添加商品
        // 商品名称必须唯一不能重复
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) {
          return this.$message.error('添加商品失败!')
        }
        this.$message.success('添加商品成功!')
        this.$router.push('/goods')
      })
      */
        this.$refs.addFormRef.validate(async valid => {
          if (!valid) return this.$message.error('请填写必要的表单项！')
          // 发送请求前：需对提交的表单进行处理goods_cat attrs
          // this.addForm.goods_cat = this.addForm.goods_cat.join(',')
          // 以上写法不对：级联选择器绑定的对象goods_cat要求是数组对象
          // 解决办法: 包：lodash 方法（深拷贝）：cloneDeep(boj)

          // 将this.addForm进行深拷贝
          const form = _.cloneDeep(this.addForm)
          form.goods_cat = form.goods_cate.join(',')

          // 处理动态参数
          this.manyTableData.forEach(item => {
            const newInfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals.join(' ')
            }
            this.addForm.attrs.push(newInfo)
          })
          // 处理静态属性
          this.onlyTableData.forEach(item => {
            const newInfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals
            }
            this.addForm.attrs.push(newInfo)
          })
          form.attrs = this.addForm.attrs
          // 发起请求添加商品
          // 商品名称必须是唯一的
          const { data: res } = await this.$http.post('goods', form)
          if (res.meta.status !== 201) return this.$message.error('添加商品失败！')
          this.$message.success('添加商品成功!')
          this.$router.push('/goods')
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .el-checkbox {
    margin: 0 5px 0 0 !important;
  }

  .previewImg {
    width: 100%;
  }
  .btnAdd {
    margin-top: 15px;
  }
</style>
